package com.hitalkie.teacher.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.adapter.MainRvAdapter;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.app.TalkieApplication;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.model.Lesson;
import com.hitalkie.teacher.model.Notification;
import com.hitalkie.teacher.tx.Constants;
import com.hitalkie.teacher.tx.MySelfInfo;
import com.hitalkie.teacher.tx.QavsdkControl;
import com.hitalkie.teacher.util.OkHttpManager;
import com.hitalkie.teacher.util.PreferencesController;
import com.hitalkie.teacher.util.Utils;
import com.hitalkie.teacher.widget.pageview.OnLastItemVisibleListener;
import com.hitalkie.teacher.widget.pageview.PageRecyclerView;
import com.tencent.TIMCallBack;
import com.tencent.TIMLogLevel;
import com.tencent.TIMManager;
import com.tencent.TIMUser;
import com.umeng.message.PushAgent;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.tag.TagManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 *
 */
public class MainActivity extends BaseActivity {

    private String mNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_main);
        signIn();
        initView();
        updateData(true);
        checkVersion();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getNotificationCount();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra("need_refresh", false)) {
            updateData(true);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 0: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the task you need to do.

                } else {
                    // permission denied, boo! Disable the functionality that depends on this permission.

                }
                break;
            }
            default:
                break;
        }
    }

    void checkPermission(Activity activity) {
        final List<String> permissionsList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);

            }
//            if ((activity.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)) {
//                permissionsList.add(Manifest.permission.READ_PHONE_STATE);
//            }
            if (permissionsList.size() != 0) {
                activity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), 0);
            }
//            permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            activity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), 0);
        }

    }

    private void signIn() {
        if (TalkieApplication.isSignIn()) {
            // 已经登录，每次启动需要腾讯的im再登录一下
            imLogin(MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
        } else {
            // 解绑 push tag
            PushAgent.getInstance(getApplicationContext()).getTagManager().reset(new TagManager.TCallBack() {
                @Override
                public void onMessage(boolean b, ITagManager.Result result) {
                    Log.e(TAG, "unbind push tag:" + b + "   " + result);

                }
            });
            // 绑定 push tag 游客
            PushAgent.getInstance(getApplicationContext()).getTagManager().add(new TagManager.TCallBack() {
                @Override
                public void onMessage(boolean isSuccess, ITagManager.Result result) {
                    Log.e(TAG, "bind push tag: isSuccess:" + isSuccess + "   " + result);
                    if (isSuccess) {
                    } else {
                    }
                }
            }, "-1");
        }

    }

    private void imLogin(final String identify, String userSig) {
        TIMUser user = new TIMUser();
        user.setAccountType(String.valueOf(Constants.ACCOUNT_TYPE));
        user.setAppIdAt3rd(String.valueOf(Constants.SDK_APPID));
        user.setIdentifier(identify);
        //发起登录请求
        TIMManager.getInstance().login(
                Constants.SDK_APPID,
                user,
                userSig,                    //用户帐号签名，由私钥加密获得，具体请参考文档
                new TIMCallBack() {
                    @Override
                    public void onError(int i, String s) {
                        Log.e(TAG, "IMLogin fail ：" + i + " msg " + s);
                        Toast.makeText(getActivity(), getText(R.string.sign_fail), Toast.LENGTH_SHORT).show();
                        TalkieApplication.signOut();
                    }

                    @Override
                    public void onSuccess() {
                        Log.i(TAG, "keypath IMLogin succ !");
//                        Toast.makeText(mContext, "IMLogin succ !", Toast.LENGTH_SHORT).show();
                        startAVSDK();
                    }
                });
    }

    private void startAVSDK() {
        QavsdkControl.getInstance().setAvConfig(Constants.SDK_APPID, "" + Constants.ACCOUNT_TYPE, MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
        QavsdkControl.getInstance().startContext();
    }

    private void initView() {
        initTitleBar();
        initSrl();
        initRv();
    }

    private void initTitleBar() {
        findViewById(R.id.ivTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TalkieApplication.isSignIn()) {
                    // 1.学生 2.外教 3.中教 4.staff 5.admin
                    if (TalkieApplication.getUserType() == 1) {
//                        startActivity(new Intent(getActivity(), MeStudentActivity.class));
                    } else if (TalkieApplication.getUserType() == 2) {
                        startActivity(new Intent(getActivity(), MeTeacherActivity.class));
                    } else {
                        Toast.makeText(getActivity(), "user type unknown", Toast.LENGTH_LONG).show();
                        startActivity(new Intent(getActivity(), SignUpActivity.class));
                    }
                } else {
                    startActivity(new Intent(getActivity(), SignUpActivity.class));
                }
            }
        });
        findViewById(R.id.ivTitleBarCenter).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                PageRecyclerView rv = (PageRecyclerView) findViewById(R.id.rv);
                rv.scrollToPosition(0);
            }
        });
    }

    private void initSrl() {
        SwipeRefreshLayout srl = (SwipeRefreshLayout) findViewById(R.id.srl);
        assert srl != null;
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updateData(true);
            }
        });
    }

    private void initRv() {
        PageRecyclerView rv = (PageRecyclerView) findViewById(R.id.rv);
        assert rv != null;
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setAdapter(new MainRvAdapter());
        ((MainRvAdapter) rv.getAdapter()).setOnItemClickListener(new MainRvAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Lesson data) {
                Intent i = new Intent(getActivity(), LessonDetailActivity.class);
                i.putExtra(LessonDetailActivity.EXTRA_LESSON, data);
                startActivity(i);
            }

        });
        rv.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!TextUtils.isEmpty(mNext)) {
                    updateData(false);
                }
            }
        });
    }

    private void updateData(final boolean isRefresh) {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");
        ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(true);

        String url = null;
        if (isRefresh) {
            url = TalkieApi.getHost() + TalkieApi.PATH_INDEX;
        } else {
            url = TalkieApi.getHost() + mNext;
        }
        Log.e(TAG, "index req:" + url);
        Request.Builder reqBuilder = new Request.Builder().url(url);
        OkHttpManager.client.newCall(reqBuilder.build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);
                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "index resp:" + jsonStr);

                        try {
                            final IndexResp resp = new Gson().fromJson(jsonStr, IndexResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp != null && resp.status.error_code == 0) {
                                        if (isRefresh) {
                                            // 刷新页面
                                            ((MainRvAdapter) ((RecyclerView) findViewById(R.id.rv)).getAdapter()).setData(resp.my_appointments, resp.lessons);
                                            updateNotificationView(resp.notification);
                                        } else {
                                            // 加载更多
                                            ((MainRvAdapter) ((RecyclerView) findViewById(R.id.rv)).getAdapter()).addData(resp.lessons);
                                        }
                                        if (TextUtils.isEmpty(resp.next)) {
                                            // 到了最后一页
                                            ((PageRecyclerView) findViewById(R.id.rv)).loadingStatus = PageRecyclerView.State.END;
                                        } else {
                                            ((PageRecyclerView) findViewById(R.id.rv)).loadingStatus = PageRecyclerView.State.IDLE;
                                        }
                                        mNext = resp.next;
                                    } else {
                                        Toast.makeText(getActivity(), resp != null ? resp.status.error_message : "获取数据时发生异常", Toast.LENGTH_LONG).show();
                                        if (resp.status.error_code == 403) {
                                            // 登录授权失败
                                            startActivity(new Intent(getActivity(), SignInActivity.class));
                                        }
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                    ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);

                                    checkPermission(getActivity());
                                    TIMManager.getInstance().setLogLevel(TIMLogLevel.INFO);
                                    Log.e(TAG, "Log level :::::::::" + TIMManager.getInstance().getLogLevel());
                                }
                            });
                        }
                    }
                });
    }

    private void checkVersion() {
        String url = TalkieApi.getHost() + TalkieApi.PATH_VERSION;
        Request.Builder reqBuilder = new Request.Builder().url(url);
        OkHttpManager.client.newCall(reqBuilder.build())
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {}

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();

                        try {
                            final VersionResp resp = new Gson().fromJson(jsonStr, VersionResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp != null && resp.status.error_code == 0) {
                                        int version = Utils.getAppVersionCode(getActivity());
                                        if (version < resp.min_version) {
                                            new AlertDialog.Builder(getActivity())
                                                    .setTitle("Current is no longer support, please update by " +
                                                            "clicking the button below")
                                                    .setPositiveButton("update", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            Utils.downloadApk(getActivity(), resp.download);
                                                        }
                                                    })
                                                    .setCancelable(false)
                                                    .show();
                                        } else if (version < resp.last_version && version >= resp.min_version) {
                                            new AlertDialog.Builder(getActivity())
                                                    .setTitle("a new update is available")
                                                    .setPositiveButton(getText(R.string.update), new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.dismiss();
                                                            Utils.downloadApk(getActivity(), resp.download);
                                                        }
                                                    })
                                                    .setNegativeButton(getText(R.string.cancel), new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.dismiss();
                                                        }
                                                    })
                                                    .show();
                                        }
                                    }
                                }
                            });
                        } catch (Exception e) {}
                    }
                });
    }

    private static class IndexResp extends BaseResponse {
        String next; // "",
        List<Lesson> my_appointments;
        int notification_unread_count;
        Notification notification;
        List<Lesson> lessons;
    }

    private static class VersionResp extends BaseResponse {
        String detail;      // 更新描述
        int last_version;   // 最新版本号
        int min_version;    // 淘汰版本号
        String download;    // 下载链接
    }

    private void updateNotificationView(Notification notification) {
        TextView tvNotification = (TextView) findViewById(R.id.tvNotification);
        if (notification == null) {
            tvNotification.setVisibility(View.GONE);
        } else if (System.currentTimeMillis() > notification.expire_time) {
            tvNotification.setVisibility(View.GONE);
        } else {
            tvNotification.setVisibility(View.VISIBLE);
            tvNotification.setText(notification.getTitle());
            tvNotification.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent().setClass(getActivity(), NotificationListActivity.class));
                }
            });
        }

    }


    private void getNotificationCount() {

        String url = TalkieApi.getHost() + TalkieApi.PATH_NOTIFICATION_COUNT;
        Request.Builder reqBuilder = new Request.Builder().url(url);
        OkHttpManager.client.newCall(reqBuilder.build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        try {
                            final NotificationCountResp resp = new Gson().fromJson(jsonStr, NotificationCountResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp != null && resp.status != null && resp.status.error_code == 0) {
                                        updateNotificationView(resp.last_notification);
                                        if (resp.evaluation_unread_count > 0) {
                                            findViewById(R.id.tvNotificationCount).setVisibility(View.VISIBLE);
                                        } else {
                                            findViewById(R.id.tvNotificationCount).setVisibility(View.GONE);
                                        }
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    Log.e(TAG, " ");
                                }
                            });
                        }
                    }
                });
    }

    private static class NotificationCountResp extends BaseResponse {
        Notification last_notification;
        int evaluation_unread_count;
    }


}
